package bourne.com.util;

import java.io.ByteArrayInputStream;
import java.util.Iterator;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPMessage;

public class SoapUtil {

	/**
	 * 把soap字符串格式化为SOAPMessage
	 * 
	 * @param soapString
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	private static SOAPMessage formatSoapString(String soapString) {
		MessageFactory msgFactory;
		try {
			msgFactory = MessageFactory.newInstance();
			SOAPMessage reqMsg = msgFactory.createMessage(new MimeHeaders(),
					new ByteArrayInputStream(soapString.getBytes("UTF-8")));
			reqMsg.saveChanges();
			return reqMsg;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 解析soap xml
	 * 
	 * @param iterator
	 * @param resultBean
	 */
	private static void parse(Iterator<SOAPElement> iterator) {
		while (iterator.hasNext()) {
			SOAPElement element = iterator.next();
			// System.out.println("Local Name:" + element.getLocalName());
			// System.out.println("Node Name:" + element.getNodeName());
			// System.out.println("Tag Name:" + element.getTagName());
			// System.out.println("Value:" + element.getValue());
			if ("ns:BASEINFO".equals(element.getNodeName())) {
				continue;
			} else if ("ns:MESSAGE".equals(element.getNodeName())) {
				Iterator<SOAPElement> it = element.getChildElements();
				SOAPElement el = null;
				while (it.hasNext()) {
					el = it.next();
					if ("RESULT".equals(el.getLocalName())) {
						System.out.println("#### " + el.getLocalName() + "  ====  " + el.getValue());
					} else if ("REMARK".equals(el.getLocalName())) {
						System.out.println("#### " + el.getLocalName() + "  ====  " + el.getValue());
					} else if ("XMLDATA".equals(el.getLocalName())) {
						System.out.println("#### " + el.getLocalName() + "  ====  " + el.getValue());
					}
				}
			}
		}
	}

	private static void PrintBody(Iterator<SOAPElement> iterator, String side) {
		while (iterator.hasNext()) {
			SOAPElement element = (SOAPElement) iterator.next();
			System.out.println("Local Name:" + element.getLocalName());
			System.out.println("Node Name:" + element.getNodeName());
			System.out.println("Tag Name:" + element.getTagName());
			System.out.println("Value:" + element.getValue());
			if (null == element.getValue() && element.getChildElements().hasNext()) {
				PrintBody(element.getChildElements(), side + "-----");
			}
		}
	}
}